<script>
export default {
  name: 'User'
}
</script>
<script setup>
import $API from '@/api/index'
import { useLayoutStore } from '@/store/modules/layout'
import { ElMessage } from 'element-plus'
import { UsersStore } from '@/model/Users.js'

import changeRoleDialog from './changeRole.dialog.vue'
import updateUserDialog from './updateUser.dialog.vue'

import { useRouter } from 'vue-router'
import { ref, onMounted, inject } from 'vue'

const userInfo = inject('userInfo')
const usersStore = new UsersStore()

const layoutStore = useLayoutStore()

const $router = useRouter()

// onMounted(() => {
//   reqGetUserInfo()
// })

// 搜索关键字收集
const keyword = ref('')
const reset = function () {
  layoutStore.changeRefresh()
}

// 用户信息
const userInfoDataArr = ref([{}])
// 请求用户信息
const reqGetUserInfo = async function (page = 1) {
  const result = await $API.acl.user.reqGetUserInfo(page, limit.value, keyword.value)

  if (result?.data?.code === 200) {
    userInfoDataArr.value = result.data.data.records
    total.value = result.data.data.total

    return 'ok'
  } else {
    return Promise.reject(result?.data?.message)
  }
}

// 用户信息编辑抽屉判定
const userInfoEditor = ref(false)
// 用户信息编辑收集
const userInfoEditorData = ref({
  name: '',
  username: '',
  password: ''
})
// 用户信息编辑收集
const userInfoEditorDataTmp = ref({
  name: '',
  username: '',
  password: ''
})
// 用户信息表单DOM
const userInfoEditorRef = ref()
// 用户信息表单在自定义校验规则
const validateName = function (rule, value, cb) {
  if (value.length < 4) {
    cb(new Error('名字至少4位'))
  } else {
    cb()
  }
}
const validateUsername = function (rule, value, cb) {
  if (value.length < 4) {
    cb(new Error('名称至少4位'))
  } else {
    cb()
  }
}
const validatePassword = function (rule, value, cb) {
  if (value.length < 6) {
    cb(new Error('密码至少6位'))
  } else {
    cb()
  }
}
const userInfoEditorValidate = {
  name: [{ required: true, validator: validateName, trigger: 'change' }],
  username: [{ required: true, validator: validateUsername, trigger: 'change' }],
  password: [{ required: true, validator: validatePassword, trigger: 'change' }]
}
// 打开用户信息编辑抽屉
const openUserInfoEditor = function (row = {}) {
  Object.assign(userInfoEditorData.value, row)
  Object.assign(userInfoEditorDataTmp.value, JSON.parse(JSON.stringify(row)))
  userInfoEditor.value = true
}
// 关闭用户信息编辑抽屉
const closeUserInfoEditor = function () {
  userInfoEditorRef.value.resetFields()
  userInfoEditorData.value = {
    name: '',
    username: '',
    password: ''
  }
  userInfoEditorDataTmp.value = {
    name: '',
    username: '',
    password: ''
  }
  userInfoEditor.value = false
}
// 保存用户信息编辑抽屉
const saveUserInfoEditor = async function (formRef) {
  if (!formRef) return
  try {
    await formRef.validate()
    const result = await $API.acl.user.reqSaveUserInfo(userInfoEditorData.value)
    if (result?.data?.code === 200) {
      ElMessage.success(userInfoEditorData.value.id ? '更新用户成功' : '添加用户成功')

      // 如果修改的是当前登录的用户应该退出重新登录
      if (userInfo.vm.data.name === userInfoEditorDataTmp.value.username) {
        await userInfo.reqLogout()
        window.location.reload()
      } else {
        reqGetUserInfo(page.value)
      }
      // 关闭抽屉
      closeUserInfoEditor()

      return 'ok'
    } else {
      return Promise.reject(result?.data?.message)
    }
  } catch (error) {
    console.log(error)
    typeof error === 'object'
      ? ElMessage.error(
          userInfoEditorData.value.id ? '更新用户失败' : '添加用户失败' + '，请检查表单项'
        )
      : ElMessage.error(userInfoEditorData.value.id ? '更新用户失败' : '添加用户失败' + error)
  }
}

// 分配角色编辑抽屉判定
const setRoleEditor = ref(false)
// 分配角色编辑收集
const setRoleEditorData = ref({
  roleIdList: [],
  userId: null
})
// 打开分配角色编辑抽屉
const openSetRoleEditor = async function (row) {
  // 打开抽屉
  setRoleEditor.value = true
  // 收集数据
  Object.assign(setRoleEditorData.value, row)
  // 发请求
  const result = await $API.acl.user.reqToAssign(row.id)
  if (result?.data?.code === 200) {
    checkedRole.value = result.data.data.assignRoles
    roleAll.value = result.data.data.allRolesList
    handleCheckedRoleAllChange(checkedRole.value)
  }
}
// 关闭分配角色编辑抽屉
const closeSetRoleEditor = function () {
  setRoleEditorData.value = {
    roleIdList: [],
    userId: null
  }
  setRoleEditor.value = false
}
// 保存分配角色编辑抽屉
const saveSetRoleEditor = async function () {
  const data = {
    roleIdList: checkedRole.value.map(item => item.id),
    userId: setRoleEditorData.value.id
  }
  const result = await $API.acl.user.reqDoAssignRole(data)
  if (result?.data?.code === 200) {
    reqGetUserInfo(page.value)
    closeSetRoleEditor()
    ElMessage.success('分配角色成功')

    return 'ok'
  } else {
    ElMessage.error('分配角色失败')
    return Promise.reject(result?.data?.message)
  }
}

// 要批量删除的用户
const removeArr = ref([])
// 表格多选框事件
const removeUsersSelectionChange = function (userArr) {
  removeArr.value = userArr
}
// 确定批量删除事件
const removeUsersConfirm = async function () {
  // 整理数据
  const data = removeArr.value.map(item => item.id)
  const result = await $API.acl.user.reqRemovers(data)
  if (result?.data?.code === 200) {
    reqGetUserInfo(page.value)
    ElMessage.success('删除成功')

    return 'ok'
  } else {
    ElMessage.error('删除失败')
    return Promise.reject(result?.data?.message)
  }
}
// 确定删除用户事件
const removeUserByUserIdConfirm = async function (userId) {
  const result = await $API.acl.user.reqRemoverByID(userId)
  if (result?.data?.code === 200) {
    reqGetUserInfo(page.value)
    ElMessage.success('删除成功')

    return 'ok'
  } else {
    ElMessage.error('删除失败')
    return Promise.reject(result?.data?.message)
  }
}

// 分页器
// 当前页码
const page = ref(1)
// 每页条数
const limit = ref(10)
// 总条数
const total = ref(0)
// 没有条数变化后的回调函数
const handleSizeChange = function () {
  reqGetUserInfo()
}
// 页码改变后的回调函数
const handleCurrentChange = function () {
  reqGetUserInfo(page.value)
}
</script>

<template>
  <div>
    <!-- 搜索框 -->
    <el-card>
      <el-form class="form">
        <el-form-item label="用户名">
          <el-input
            style="width: 250px"
            placeholder="请输入用户名"
            v-model="keyword"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :disabled="!keyword"
            @click="reqGetUserInfo()"
            >搜索</el-button
          >
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户表格 -->
    <el-card class="marginTop20px">
      <!-- 按钮 -->
      <div class="tableBtn">
        <el-button
          type="primary"
          @click="openUserInfoEditor()"
          v-has="'btn.User.add'"
        >
          添加
        </el-button>
        <el-popconfirm
          title="确定要删除这些用户吗？"
          @confirm="removeUsersConfirm"
        >
          <template #reference>
            <el-button
              type="warning"
              :disabled="removeArr.length === 0"
              v-has="'btn.User.remove'"
            >
              批量删除
            </el-button>
          </template>
        </el-popconfirm>
      </div>

      <!-- 表格 -->
      <xTable
        :store="usersStore"
        class="marginTop20px"
        border
        stripe
      >
        <el-table-column
          type="selection"
          align="center"
          width="80"
        />
        <el-table-column
          label="#"
          align="center"
          width="80"
        >
          <template #="{ $index }">
            <span>{{ $index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="id"
          label="id"
          align="center"
          width="80"
          show-overflow-tooltip
        />
        <el-table-column
          prop="name"
          label="用户名字"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          prop="username"
          label="用户名称"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          prop="roleName"
          label="用户角色"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="updateTime"
          label="更新时间"
          min-width="150"
          show-overflow-tooltip
        />
        <xTableColumn
          show-overflow-tooltip
          label="操作"
          align="center"
          min-width="350"
        >
          <xTabelActionDialogButton
            type="drawer"
            title="分配角色"
            icon="User"
            :refresh="true"
            :target="changeRoleDialog"
          >
            分配角色
          </xTabelActionDialogButton>

          <xTabelActionDialogButton
            type="drawer"
            title="编辑用户"
            icon="Edit"
            :refresh="true"
            :target="updateUserDialog"
          >
            编辑用户
          </xTabelActionDialogButton>
          <xTableActionDeleteButton label="username" />
        </xTableColumn>
      </xTable>
    </el-card>

    <!-- 添加&编辑用户抽屉 -->
    <!-- <el-drawer
      v-model="userInfoEditor"
      :title="userInfoEditorData.id ? '修改用户' : '添加用户'"
      direction="rtl"
      @closed="closeUserInfoEditor()"
    >
      <el-form
        label-width="80px"
        :model="userInfoEditorData"
        ref="userInfoEditorRef"
        :rules="userInfoEditorValidate"
      >
        <el-form-item
          label="用户姓名"
          prop="name"
        >
          <el-input
            v-model="userInfoEditorData.name"
            placeholder="请填写用户姓名"
          />
        </el-form-item>
        <el-form-item
          label="用户名称"
          prop="username"
        >
          <el-input
            v-model="userInfoEditorData.username"
            placeholder="请填写用户名称"
          />
        </el-form-item>
        <el-form-item
          label="用户密码"
          prop="password"
          v-if="!userInfoEditorData.id"
        >
          <el-input
            v-model="userInfoEditorData.password"
            placeholder="请填写用户密码"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeUserInfoEditor()">取消</el-button>
        <el-button
          type="primary"
          @click="saveUserInfoEditor(userInfoEditorRef)"
        >
          确定
        </el-button>
      </template>
    </el-drawer> -->
  </div>
</template>

<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-form-item {
    margin-bottom: 0;
  }
}
</style>
